package com.ys.controller.api.outer;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.constant.AppConstant;
import com.ys.entity.sys.TsUserInfo;
import com.ys.service.sys.ImgcodeService;
import com.ys.util.dh.DhPassUtil;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/outer")
public class ApiOuterController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);


    @Autowired
    private ImgcodeService imgcodeService;
	
	@PostMapping("/login")
	@ResponseBody
	public R login(
    		Model model,
			HttpServletRequest request,
			HttpServletResponse response,
			String loginName,
			String pass
			) {
		
		if (loginName == null || loginName.length() == 0) {
			return R.error("登录名不能为空");
		} else if (pass == null || pass.length() == 0) {
			return R.error("密码不能为空");
		}
		
		TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginName).queryFirst();
		if (tsUserInfo == null) {
			return R.error("用户不存在");
		} else if (tsUserInfo.getRoleId() == null) {
			return R.error("尚未设置岗位，请联系管理员设置");
		} else if (tsUserInfo.getStatus() == 0) {
			return R.error("用户状态未启用");
		}

		String passEncrypt = DhPassUtil.encryptPassword(loginName, pass, AppConstant.PASSWORD_SALT);
		if (!passEncrypt.equals(tsUserInfo.getUserPassWord())) {
			return R.error("密码不正确");
		}
		
		imgcodeService.doAuthAfterLogin(tsUserInfo);
		return R.ok();
	}

	@RequestMapping("/code")
	public void code(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		imgcodeService.getImgCode(request, response);
	}
	
}
